

class Ballr {
    constructor(ctx,canvas,index,img) {
        this.r = 30
        this.x = this.rand(canvas.width - this.r * 2); //小球初始横坐标
        this.y = this.rand(canvas.height - this.r * 2); //小球初始纵坐标
        this.color = index; //小球颜色，以下标表示
        this.img = img; //小球素材
        this.ctx=ctx
        this.canvas=canvas
        this.speedX=null
        this.speedY=null
    }

    static getInstance() {
        if (!this.instance) {
            this.instance = new Ballr()
            do {
                this.speedX = this.rand(20) - 10;
            } while (this.speedX < 5); //小球横坐标改变速度
            do {
                this.speedY = this.rand(20) - 10;
            } while (this.speedY < 5); //小球纵坐标改变速度
        }
        return this.instance
    }
    rand(num) {
        //随机数
        return Math.random() * num;
    }
    run() {
        // console.log('//',this)
        this.x += this.speedX;
        this.y += this.speedY;
        if (this.x > this.canvas.width - this.r * 2) {
            //小球碰到右边界，横坐标速度变为负
            this.speedX = -this.speedX;
        }
        if (this.x < 0) {
            //小球碰到左边界，横坐标速度变为正
            this.speedX = Math.abs(this.speedX);
        }
        if (this.y > this.canvas.height - this.r * 2) {
            //小球碰到下边界，纵坐标速度变为负
            this.speedY = -this.speedY;
        }
        if (this.y < 0) {
            //小球碰到上边界，纵坐标速度变为正
            this.speedY = Math.abs(this.speedY);
        }
        console.log(this)
        this.ctx.drawImage(this.path, this.x, this.y, 60, 60); //绘制小球

    }

}
export default Ballr